package br.com.sig.security.business.model.bo;

import javax.ejb.Stateless;
import javax.inject.Named;

import org.hibernate.criterion.MatchMode;

import br.com.sig.business.exception.BaseException;
import br.com.sig.business.model.BaseService;
import br.com.sig.security.business.model.entity.User;

/**
 * Session Bean implementation class TesteBO
 */
@Named
@Stateless
public class UserBO extends BaseService<User> {

	private static final long serialVersionUID = 816936296433007811L;
	
	public void changePassword(User user, String currentPassword, String newPassword) throws BaseException {
		
		if (currentPassword == null || currentPassword.isEmpty()) {
			throw new BaseException("error.change.password.current.password.not.informed");
		}
		
		if (newPassword == null || newPassword.isEmpty()) {
			throw new BaseException("error.change.password.new.password.not.informed");
		}
		
		if (user == null) {
			throw new BaseException("error.change.password.invalid.user");
		}
		
		if (!user.getPassword().equals(currentPassword)) {
			throw new BaseException("error.change.password.invalid.password");
		}
		
		user.setPassword(newPassword);
		update(user);
	}
	
	public User findByUserName(String userName) throws BaseException {
		return findSingleResult(new User(userName), MatchMode.EXACT);
	}
	
	public void restorePassword(String userName) throws BaseException {
		User user = findByUserName(userName);
		changePassword(user, user.getPassword(), user.getFuncionario().getPessoaFisica().getCpf());
	}

}